package com.cyj.dream.security.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.cyj.dream.core.constant.SecurityConstants;
import com.cyj.dream.upms.model.dto.UserInfo;
import com.cyj.dream.upms.service.SosUser;
import lombok.experimental.UtilityClass;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * @Description: 安全工具类
 * @BelongsProject: DreamChardonnay
 * @BelongsPackage: com.cyj.dream.security.annotation
 * @Author: ChenYongJia
 * @CreateTime: 2021-10-19 13:30
 * @Email: chen87647213@163.com
 * @Version: 1.0
 */
@UtilityClass
public class SecurityUtils {

    /**
     * 获取Authentication
     */
    public Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 获取用户
     */
    public SosUser getUser(Authentication authentication) {
        Object principal = authentication.getPrincipal();
        if (principal instanceof SosUser) {
            return (SosUser) principal;
        }
        return null;
    }

    /**
     * 获取用户
     */
    public SosUser getUser() {
        Authentication authentication = getAuthentication();
        if (authentication == null) {
            return null;
        }
        return getUser(authentication);
    }


    /**
     * 外部获取用户
     */
    public UserInfo externalGetUser() {
        Authentication authentication = getAuthentication();
        if (authentication == null) {
            return null;
        }
        UserInfo userInfo = null;
        try {
            Map pageUser = (Map) authentication.getPrincipal();
            if (pageUser.get(SecurityConstants.DETAILS_USERINFO) != null) {
                userInfo = BeanUtil.mapToBean((Map) pageUser.get(SecurityConstants.DETAILS_USERINFO), UserInfo.class, false);
            }

        } catch (Exception e) {
            //登录状态过期
            e.printStackTrace();
        }
        return userInfo;
    }

    /**
     * 获取用户角色信息
     *
     * @return 角色集合
     */
    public List<Integer> getRoles() {
        Authentication authentication = getAuthentication();
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();

        List<Integer> roleIds = new ArrayList<>();
        authorities.stream().filter(granted -> StrUtil.startWith(granted.getAuthority(), SecurityConstants.ROLE))
                .forEach(granted -> {
                    String id = StrUtil.removePrefix(granted.getAuthority(), SecurityConstants.ROLE);
                    roleIds.add(Integer.parseInt(id));
                });
        return roleIds;
    }

}
